﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;

namespace MS.InformationManagement.BLL.DocumentPrinter
{
    public class UpdateDocumentStatusDelivery : IBaseCommand
    {

        #region Fields

        IEnumerable<EnvíoDeCorrespondencia> _documentsSent;

        #endregion

        #region Constructors

        public UpdateDocumentStatusDelivery(IEnumerable<EnvíoDeCorrespondencia> documentsSent)
        {
            _documentsSent = documentsSent;
        }

        #endregion

        #region Implemented Command Methods

        public void Execute()
        {
            setDocumentStatus(true);
        }

        public void Undo()
        {
            setDocumentStatus(false);
        }

        #endregion

        #region Private

        private void setDocumentStatus(bool newStatus)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        foreach (var deliveryEntity in _documentsSent)
                        {
                            SPFolder currentDocument = currentWeb.Lists[deliveryEntity.BibliotecaDelDocumento].GetItemById(Convert.ToInt16(deliveryEntity.IdDocumento)).Folder;
                            currentDocument.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_SENT] = newStatus;
                            currentDocument.Item.Update();
                            currentDocument.Update();
                        }
                    }
                }
            });     

        }

        #endregion

    }
}
